package com.ruoyi.chat.service.impl;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.chat.domain.Friendship;
import com.ruoyi.chat.domain.SysUser;
import com.ruoyi.chat.service.IFriendshipService;
import com.ruoyi.chat.service.ISysUserService;
import com.ruoyi.chat.vo.HistoryMessageVO;
import com.ruoyi.common.core.vo.ChatListVO;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.chat.mapper.ChatMessageMapper;
import com.ruoyi.chat.domain.ChatMessage;
import com.ruoyi.chat.service.IChatMessageService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;

/**
 * 聊天信息存储Service业务层处理
 * 
 * @author zhc
 * @date 2025-05-31
 */
@Service
public class ChatMessageServiceImpl implements IChatMessageService 
{
    @Autowired
    private ChatMessageMapper chatMessageMapper;
    @Resource
    private ISysUserService userService;
    @Resource
    private IFriendshipService iFriendshipService;

    /**
     * 查询聊天信息存储
     * 
     * @param id 聊天信息存储主键
     * @return 聊天信息存储
     */
    @Override
    public ChatMessage selectChatMessageById(String id)
    {
        return chatMessageMapper.selectChatMessageById(id);
    }

    /**
     * 查询聊天信息存储列表
     * 
     * @param chatMessage 聊天信息存储
     * @return 聊天信息存储
     */
    @Override
    public List<ChatMessage> selectChatMessageList(ChatMessage chatMessage)
    {
        return chatMessageMapper.selectChatMessageList(chatMessage);
    }

    /**
     * 新增聊天信息存储
     * 
     * @param chatMessage 聊天信息存储
     * @return 结果
     */
    @Override
    @Transactional
    public int insertChatMessage(ChatMessage chatMessage)
    {
        return chatMessageMapper.insertChatMessage(chatMessage);
    }

    /**
     * 修改聊天信息存储
     * 
     * @param chatMessage 聊天信息存储
     * @return 结果
     */
    @Override
    public int updateChatMessage(ChatMessage chatMessage)
    {
        return chatMessageMapper.updateChatMessage(chatMessage);
    }

    /**
     * 批量删除聊天信息存储
     * 
     * @param ids 需要删除的聊天信息存储主键
     * @return 结果
     */
    @Override
    public int deleteChatMessageByIds(String[] ids)
    {
        return chatMessageMapper.deleteChatMessageByIds(ids);
    }

    /**
     * 删除聊天信息存储信息
     * 
     * @param id 聊天信息存储主键
     * @return 结果
     */
    @Override
    public int deleteChatMessageById(String id)
    {
        return chatMessageMapper.deleteChatMessageById(id);
    }

    @Override
    public List<ChatListVO> queryChatList() {
        List<String> userIds=new ArrayList<>();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        //根据接收方或者发送方groupby，可能会查出两份数据，需要过滤自己是接收方的是最新的消息还是自己的发送方是最新的消息
        List<ChatMessage> chatMessageList=chatMessageMapper.queryChatList(loginUser.getUserid());
        if(CollectionUtils.isEmpty(chatMessageList)){
            return new ArrayList<>();
        }
        List<ChatListVO> res=new ArrayList<>();
        //对手id->最新的chatMessage
        Map<String,ChatMessage> messageMap=new HashMap<>();
        //chatMessageList,查找真正最新的消息
        chatMessageList.forEach(chatMessage -> {
            boolean isCurrentUserSender=chatMessage.getSenderId().equals(String.valueOf(loginUser.getUserid()));
            String userId=isCurrentUserSender?chatMessage.getReceiverId():chatMessage.getSenderId();
            userIds.add(userId);
            if(!messageMap.containsKey(userId)){
                messageMap.put(userId,chatMessage);
            }
            else if(messageMap.get(userId).getChatTime().before(chatMessage.getChatTime())){
                messageMap.put(userId,chatMessage);
            }
        });
        Map<String,SysUser> sysUsersMap = userService.selectSysUserByUserIds(userIds);
        Map<String, Friendship> friendshipMap = iFriendshipService.convertToMap(iFriendshipService.queryFriend());
        List<ChatMessage> collect = messageMap.values().stream().sorted((o1, o2) -> o2.getChatTime().compareTo(o1.getChatTime())).collect(Collectors.toList());
        for(ChatMessage chatMessage:collect){
            boolean isCurrentUserSender=chatMessage.getSenderId().equals(String.valueOf(loginUser.getUserid()));
            String userId=isCurrentUserSender?chatMessage.getReceiverId():chatMessage.getSenderId();
            SysUser curUser = sysUsersMap.get(userId);
            Friendship friendship = friendshipMap.get(userId);
            ChatListVO chatListVO = new ChatListVO();
            chatListVO.setLatestMessage(chatMessage.getMsg());
            chatListVO.setAvatar(curUser.getAvatar());
            chatListVO.setNickName(friendship.getFriendRemark());
            chatListVO.setUserId(userId);
            chatListVO.setLatestMessage(chatMessage.getMsg());
            chatListVO.setLatestMessageTime(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(chatMessage.getChatTime()));
            chatListVO.setIsLatestMessageSender(isCurrentUserSender);
            res.add(chatListVO);
        }
        return res;
    }

    @Override
    public List<HistoryMessageVO> queryChatHistory(String userId) {
        //todo 缓存
        LoginUser loginUser = SecurityUtils.getLoginUser();
        List<HistoryMessageVO> historyMessageVOS = chatMessageMapper.queryChatHistory(loginUser.getUserid(), userId);
        historyMessageVOS.forEach(historyMessageVO -> historyMessageVO.setSender(historyMessageVO.getSenderId().equals(String.valueOf(loginUser.getUserid()))));
        return historyMessageVOS;
    }
}
